Jupyter notebook交互输入方法(ipywidgets控件),包括文本框text input box,按钮button等 |
您所在的位置:网站首页 › python input 换行等待输入 › Jupyter notebook交互输入方法(ipywidgets控件),包括文本框text input box,按钮button等 |
交互式输入用到的包是ipywidgets,如果还未安装,可以在终端中使用pip install ipywidgets安装。 如果安装后无法正常显示控件,请在终端运行jupyter nbextension enable --py widgetsnbextension --sys-prefix。 如果你是jupyter lab用户,请运行jupyter labextension install @jupyter-widgets/jupyterlab-manager并重启Jupyter lab,同时确保Jupyter lab侧边栏的Extension Manager是启用状态。 引用: import ipywidgets as widgets # 控件库 from IPython.display import display # 显示控件的方法官方文档:https://ipywidgets.readthedocs.io/en/stable/index.html Github项目地址:https://github.com/jupyter-widgets/ipywidgets widgets中的控件包括两部分: UI/HTML element,这是显示在output cell中的部分,通常是实例化后将其作为display函数的实参传递 event handler,控件的注册事件,通常做法是将一个定义好的python函数作为实参传递到控件的事件中 例子 - TextBox import ipywidgets as widgets # 控件库 from IPython.display import display # 显示控件的方法 text = widgets.Text() display(text) def print_value(sender): print(sender.value) text.on_submit(print_value) # 回车以提交内容
widgets.Text():文本框,构造函数没有形参,常用事件.on_submit(callback),使用示例见上文 widgets.Button(**kwages):按钮,构造函数的形参包括: description:显示在按钮上的文字 tooltip:鼠标悬浮时显示的提示文字 icon:图标(没有成功使用过) disabled:bool值,是否禁止交互常用事件:.on_click(callback)。例子: btn = widgets.Button(description = "OK", tooltip = 'this is a button') def btn_click(sender): print('Button %s clicked!' % sender.description) btn.on_click(btn_click) display(btn)![]() 如果觉得使用Box比较麻烦,可以直接在display()里传入多个控件,也能达到组合效果,但是布局就比较随机了。比如上面的例子也可以直接使用 display(text,btn)。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |